//
//  WKOAuthController.swift
//  WKWeibo
//
//  Created by 恋guang年 on 16/3/26.
//  Copyright © 2016年 恋guang年. All rights reserved.
//

import UIKit
import SVProgressHUD

class WKOAuthController: UIViewController {
    //设置控制器的view为webVeiw
    override func loadView() {
        view = webView
        webView.delegate = self
        
        
        setUPNavigationBar()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新浪微博"
        view.backgroundColor = UIColor.whiteColor()
        // 使用webView加载登陆界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    /// 设置导航栏
    private func setUPNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    }
    
    /// 导航栏按钮点击事件!!!@objc!!!
    @objc private func autoFill(){
        //        print(__FUNCTION__)
        let jscode = "document.getElementById('userId').value='18578243419';document.getElementById('passwd').value='LWK18364151508'"
        //用此方法完成传出JS代码 相当于在HTML上执行
        webView.stringByEvaluatingJavaScriptFromString(jscode)
    }
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    //MARK: - 懒加载
    private lazy var webView:UIWebView = UIWebView()
}

//MARK: - webView代理方法
extension WKOAuthController:UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let  urlString = request.URL!.absoluteString
        print("[url:\(urlString)]")
        
        /*
        请求授权地址:https://api.weibo.com/oauth2/authorize?client_id=699521178&redirect_uri=http://www.baidu.com
        用户登录成功地址https://api.weibo.com/oauth2/authorize
        用户点击取消 http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        用户点击授权 http://www.baidu.com/?code=286e8f10077afb13dc45baf5c4f183d7
        */
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消
        //请求授权成功后 即用户点击同意授权后 加载的URL会有一个code参数 获得此参数在根据获得授权步骤 获得accessToken
        if !urlString.hasPrefix(redirect_uri){
            return true
        }else{
            //获得get请求后的参数
            let query = request.URL!.query
            let flag = "code="
            //如果参数以code=为前缀说明用户点击的是确认授权
            if query!.hasPrefix(flag){
                let queryNS = query! as NSString
                let code = queryNS.substringFromIndex(flag.characters.count)
                //获得授权
                WKUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil{
                        print("error:\(error)")
                        SVProgressHUD.showErrorWithStatus("获取授权失败")
                        self.cancel()
                    }
                    print("加载accessToken成功")
                    
                    //切换appdelegat的根控制器为欢迎控制器
                    AppDelegate.outSwitchAppDelegateRootViewController(WKWelcomeController())
                    
                    self.cancel()
                    SVProgressHUD.dismiss()
                })
            }
            else{
                //如果点击取消
                cancel()
                SVProgressHUD.dismiss()
            }
            
        }
        return false
    }
    //    ///  获取收取 得到AccessToken
    //    ///
    //    ///  - parameter code: 请求授权成功得到的code
    //    func loadAccessToken(code : String){
    //        let urlString = "https://api.weibo.com/oauth2/access_token"
    //        /*
    //          根据新浪API文档要求拼接POST请求参数
    //        */
    //
    //        let parameters = ["client_id":client_id,
    //            "client_secret":client_secret,
    //            "grant_type":"authorization_code",
    //            "code":code,
    //            "redirect_uri":redirect_uri]
    //
    //     //发送请求
    //        WKNetWorkTool.sharedInstance.afnNetWorkTool.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
    //            print("请求成功result=\(result)")
    //            }) { (_, error) -> Void in
    //                print("请求出错error=\(error)")
    //        }
    //
    //    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        //弹出正在加载提示 showWithStatus需要主动关闭
        SVProgressHUD.showWithStatus("正在加载")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭第三方提示框
        SVProgressHUD.dismiss()
    }
}




















